<template>
  <div class="system-settings">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-left">
        <h1 class="page-title">系统设置</h1>
        <div class="status-badges">
          <el-tag type="primary" class="total-badge">
            <el-icon><Setting /></el-icon>
            系统配置项: {{ stats.totalSettings }}
          </el-tag>
          <el-tag type="success" class="active-badge">
            <el-icon><Check /></el-icon>
            已启用: {{ stats.activeSettings }}
          </el-tag>
          <el-tag type="warning" class="pending-badge">
            <el-icon><Warning /></el-icon>
            待配置: {{ stats.pendingSettings }}
          </el-tag>
        </div>
      </div>
      
      <div class="header-actions">
        <!-- 保存设置 -->
        <el-button 
          type="primary" 
          :icon="Check" 
          @click="saveSettings"
          :loading="saving"
        >
          保存设置
        </el-button>
        
        <!-- 恢复默认 -->
        <el-button 
          :icon="Refresh" 
          @click="resetToDefault"
        >
          恢复默认
        </el-button>
        
        <!-- 导出配置 -->
        <el-button :icon="Download" @click="exportSettings">
          导出配置
        </el-button>
        
        <!-- 刷新数据 -->
        <el-button 
          :icon="Refresh" 
          @click="loadSettings"
          :loading="loading"
        >
          刷新
        </el-button>
      </div>
    </div>

    <!-- 统计概览 -->
    <el-row :gutter="16" class="stats-row">
      <el-col :xs="24" :sm="6">
        <div class="metric-card-wrapper">
          <div class="metric-card-custom">
            <div class="metric-icon" style="background-color: #1890ff20">
              <el-icon color="#1890ff" :size="24">
                <InfoFilled />
              </el-icon>
            </div>
            <div class="metric-info">
              <div class="metric-value">{{ stats.version }}</div>
              <div class="metric-title">系统版本</div>
            </div>
          </div>
        </div>
      </el-col>
      <el-col :xs="24" :sm="6">
        <div class="metric-card-wrapper">
          <div class="metric-card-custom">
            <div class="metric-icon" style="background-color: #52c41a20">
              <el-icon color="#52c41a" :size="24">
                <Timer />
              </el-icon>
            </div>
            <div class="metric-info">
              <div class="metric-value">{{ stats.uptime }}</div>
              <div class="metric-title">运行时长</div>
            </div>
          </div>
        </div>
      </el-col>
      <el-col :xs="24" :sm="6">
        <MetricCard
          title="内存使用"
          :value="stats.memoryUsage"
          suffix="%"
          :icon="DataLine"
          color="#fa8c16"
        />
      </el-col>
      <el-col :xs="24" :sm="6">
        <MetricCard
          title="CPU使用"
          :value="stats.cpuUsage"
          suffix="%"
          :icon="Cpu"
          color="#722ed1"
        />
      </el-col>
    </el-row>

    <!-- 设置分类导航 -->
    <el-card class="nav-card" shadow="never">
      <el-tabs v-model="activeTab" class="settings-tabs">
        <el-tab-pane label="基础设置" name="basic">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-card class="setting-card">
                <template #header>
                  <div class="setting-header">
                    <el-icon><Document /></el-icon>
                    <span>系统信息</span>
                  </div>
                </template>
                
                <el-form :model="basicSettings.systemInfo" label-width="120px">
                  <el-form-item label="系统名称">
                    <el-input v-model="basicSettings.systemInfo.name" />
                  </el-form-item>
                  
                  <el-form-item label="系统描述">
                    <el-input 
                      v-model="basicSettings.systemInfo.description" 
                      type="textarea"
                      :rows="3"
                    />
                  </el-form-item>
                  
                  <el-form-item label="系统版本">
                    <el-input v-model="basicSettings.systemInfo.version" disabled />
                  </el-form-item>
                  
                  <el-form-item label="版权信息">
                    <el-input v-model="basicSettings.systemInfo.copyright" />
                  </el-form-item>
                </el-form>
              </el-card>
            </el-col>
            
            <el-col :span="12">
              <el-card class="setting-card">
                <template #header>
                  <div class="setting-header">
                    <el-icon><Operation /></el-icon>
                    <span>系统行为</span>
                  </div>
                </template>
                
                <el-form :model="basicSettings.systemBehavior" label-width="120px">
                  <el-form-item label="自动保存">
                    <el-switch v-model="basicSettings.systemBehavior.autoSave" />
                    <div class="form-tip">自动保存用户操作</div>
                  </el-form-item>
                  
                  <el-form-item label="自动刷新">
                    <el-switch v-model="basicSettings.systemBehavior.autoRefresh" />
                    <div class="form-tip">定期刷新数据</div>
                  </el-form-item>
                  
                  <el-form-item label="刷新间隔">
                    <el-slider 
                      v-model="basicSettings.systemBehavior.refreshInterval" 
                      :min="30"
                      :max="300"
                      :step="30"
                      show-input
                    />
                    <div class="form-tip">数据刷新间隔（秒）</div>
                  </el-form-item>
                  
                  <el-form-item label="主题模式">
                    <el-select v-model="basicSettings.systemBehavior.theme" style="width: 100%">
                      <el-option label="浅色模式" value="light" />
                      <el-option label="深色模式" value="dark" />
                      <el-option label="跟随系统" value="auto" />
                    </el-select>
                  </el-form-item>
                </el-form>
              </el-card>
            </el-col>
          </el-row>
        </el-tab-pane>
        
        <el-tab-pane label="安全设置" name="security">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-card class="setting-card">
                <template #header>
                  <div class="setting-header">
                    <el-icon><Lock /></el-icon>
                    <span>密码策略</span>
                  </div>
                </template>
                
                <el-form :model="securitySettings.passwordPolicy" label-width="150px">
                  <el-form-item label="最小密码长度">
                    <el-input-number 
                      v-model="securitySettings.passwordPolicy.minLength" 
                      :min="6"
                      :max="32"
                    />
                  </el-form-item>
                  
                  <el-form-item label="必须包含数字">
                    <el-switch v-model="securitySettings.passwordPolicy.requireNumber" />
                  </el-form-item>
                  
                  <el-form-item label="必须包含特殊字符">
                    <el-switch v-model="securitySettings.passwordPolicy.requireSpecialChar" />
                  </el-form-item>
                  
                  <el-form-item label="密码过期时间">
                    <el-select 
                      v-model="securitySettings.passwordPolicy.expirationDays" 
                      style="width: 100%"
                    >
                      <el-option label="永不过期" :value="0" />
                      <el-option label="30天" :value="30" />
                      <el-option label="90天" :value="90" />
                      <el-option label="180天" :value="180" />
                    </el-select>
                    <div class="form-tip">密码必须定期更换</div>
                  </el-form-item>
                  
                  <el-form-item label="登录失败锁定">
                    <el-switch v-model="securitySettings.loginSecurity.lockOnFailedAttempts" />
                  </el-form-item>
                  
                  <el-form-item label="最大失败次数" v-if="securitySettings.loginSecurity.lockOnFailedAttempts">
                    <el-input-number 
                      v-model="securitySettings.loginSecurity.maxFailedAttempts" 
                      :min="1"
                      :max="10"
                    />
                  </el-form-item>
                  
                  <el-form-item label="锁定时间(分钟)" v-if="securitySettings.loginSecurity.lockOnFailedAttempts">
                    <el-input-number 
                      v-model="securitySettings.loginSecurity.lockDuration" 
                      :min="1"
                      :max="1440"
                    />
                  </el-form-item>
                </el-form>
              </el-card>
            </el-col>
            
            <el-col :span="12">
              <el-card class="setting-card">
                <template #header>
                  <div class="setting-header">
                    <el-icon><Bell /></el-icon>
                    <span>通知设置</span>
                  </div>
                </template>
                
                <el-form :model="securitySettings.notifications" label-width="120px">
                  <el-form-item label="登录通知">
                    <el-switch v-model="securitySettings.notifications.loginNotification" />
                    <div class="form-tip">用户登录时发送通知</div>
                  </el-form-item>
                  
                  <el-form-item label="异常登录提醒">
                    <el-switch v-model="securitySettings.notifications.suspiciousLoginAlert" />
                  </el-form-item>
                  
                  <el-form-item label="密码修改通知">
                    <el-switch v-model="securitySettings.notifications.passwordChangeNotification" />
                  </el-form-item>
                  
                  <el-form-item label="系统安全事件">
                    <el-switch v-model="securitySettings.notifications.securityEventNotification" />
                  </el-form-item>
                  
                  <el-form-item label="通知方式">
                    <el-checkbox-group v-model="securitySettings.notifications.notificationMethods">
                      <el-checkbox value="email">邮件</el-checkbox>
                      <el-checkbox value="sms">短信</el-checkbox>
                      <el-checkbox value="system">系统消息</el-checkbox>
                    </el-checkbox-group>
                  </el-form-item>
                </el-form>
              </el-card>
            </el-col>
          </el-row>
        </el-tab-pane>
        
        <el-tab-pane label="网络设置" name="network">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-card class="setting-card">
                <template #header>
                  <div class="setting-header">
                    <el-icon><DataLine /></el-icon>
                    <span>API配置</span>
                  </div>
                </template>
                
                <el-form :model="networkSettings.api" label-width="120px">
                  <el-form-item label="API超时时间">
                    <el-input-number 
                      v-model="networkSettings.api.timeout" 
                      :min="1000"
                      :max="60000"
                      :step="1000"
                    />
                    <div class="form-tip">毫秒</div>
                  </el-form-item>
                  
                  <el-form-item label="重试次数">
                    <el-input-number 
                      v-model="networkSettings.api.retryCount" 
                      :min="0"
                      :max="5"
                    />
                  </el-form-item>
                  
                  <el-form-item label="请求频率限制">
                    <el-switch v-model="networkSettings.api.rateLimiting" />
                  </el-form-item>
                  
                  <el-form-item label="每分钟请求数" v-if="networkSettings.api.rateLimiting">
                    <el-input-number 
                      v-model="networkSettings.api.requestsPerMinute" 
                      :min="10"
                      :max="10000"
                    />
                  </el-form-item>
                </el-form>
              </el-card>
            </el-col>
            
            <el-col :span="12">
              <el-card class="setting-card">
                <template #header>
                  <div class="setting-header">
                    <el-icon><Connection /></el-icon>
                    <span>代理设置</span>
                  </div>
                </template>
                
                <el-form :model="networkSettings.proxy" label-width="120px">
                  <el-form-item label="启用代理">
                    <el-switch v-model="networkSettings.proxy.enabled" />
                  </el-form-item>
                  
                  <el-form-item label="代理地址" v-if="networkSettings.proxy.enabled">
                    <el-input v-model="networkSettings.proxy.host" placeholder="例如: 192.168.1.100" />
                  </el-form-item>
                  
                  <el-form-item label="代理端口" v-if="networkSettings.proxy.enabled">
                    <el-input-number 
                      v-model="networkSettings.proxy.port" 
                      :min="1"
                      :max="65535"
                    />
                  </el-form-item>
                  
                  <el-form-item label="认证方式" v-if="networkSettings.proxy.enabled">
                    <el-select v-model="networkSettings.proxy.authType" style="width: 100%">
                      <el-option label="无认证" value="none" />
                      <el-option label="基本认证" value="basic" />
                    </el-select>
                  </el-form-item>
                  
                  <template v-if="networkSettings.proxy.enabled && networkSettings.proxy.authType === 'basic'">
                    <el-form-item label="用户名">
                      <el-input v-model="networkSettings.proxy.username" />
                    </el-form-item>
                    
                    <el-form-item label="密码">
                      <el-input 
                        v-model="networkSettings.proxy.password" 
                        type="password" 
                        show-password 
                      />
                    </el-form-item>
                  </template>
                </el-form>
              </el-card>
            </el-col>
          </el-row>
        </el-tab-pane>
        
        <el-tab-pane label="数据设置" name="data">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-card class="setting-card">
                <template #header>
                  <div class="setting-header">
                    <el-icon><DataLine /></el-icon>
                    <span>数据备份</span>
                  </div>
                </template>
                
                <el-form :model="dataSettings.backup" label-width="120px">
                  <el-form-item label="自动备份">
                    <el-switch v-model="dataSettings.backup.autoBackup" />
                  </el-form-item>
                  
                  <el-form-item label="备份频率">
                    <el-select 
                      v-model="dataSettings.backup.frequency" 
                      style="width: 100%"
                      :disabled="!dataSettings.backup.autoBackup"
                    >
                      <el-option label="每天" value="daily" />
                      <el-option label="每周" value="weekly" />
                      <el-option label="每月" value="monthly" />
                    </el-select>
                  </el-form-item>
                  
                  <el-form-item label="保留备份数">
                    <el-input-number 
                      v-model="dataSettings.backup.keepBackups" 
                      :min="1"
                      :max="100"
                      :disabled="!dataSettings.backup.autoBackup"
                    />
                  </el-form-item>
                  
                  <el-form-item label="备份路径">
                    <el-input v-model="dataSettings.backup.backupPath" />
                  </el-form-item>
                  
                  <el-form-item>
                    <el-button type="primary" @click="manualBackup">
                      立即备份
                    </el-button>
                  </el-form-item>
                </el-form>
              </el-card>
            </el-col>
            
            <el-col :span="12">
              <el-card class="setting-card">
                <template #header>
                  <div class="setting-header">
                    <el-icon><Delete /></el-icon>
                    <span>数据清理</span>
                  </div>
                </template>
                
                <el-form :model="dataSettings.cleanup" label-width="150px">
                  <el-form-item label="自动清理日志">
                    <el-switch v-model="dataSettings.cleanup.autoCleanupLogs" />
                  </el-form-item>
                  
                  <el-form-item label="日志保留天数">
                    <el-input-number 
                      v-model="dataSettings.cleanup.logRetentionDays" 
                      :min="1"
                      :max="365"
                      :disabled="!dataSettings.cleanup.autoCleanupLogs"
                    />
                  </el-form-item>
                  
                  <el-form-item label="自动清理缓存">
                    <el-switch v-model="dataSettings.cleanup.autoCleanupCache" />
                  </el-form-item>
                  
                  <el-form-item label="缓存保留天数">
                    <el-input-number 
                      v-model="dataSettings.cleanup.cacheRetentionDays" 
                      :min="1"
                      :max="365"
                      :disabled="!dataSettings.cleanup.autoCleanupCache"
                    />
                  </el-form-item>
                  
                  <el-form-item>
                    <el-button type="warning" @click="manualCleanup">
                      立即清理
                    </el-button>
                  </el-form-item>
                </el-form>
              </el-card>
            </el-col>
          </el-row>
        </el-tab-pane>
      </el-tabs>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from '@vue/runtime-core'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  Setting, Check, Warning, Refresh, Download, Document, Operation, 
  InfoFilled, Timer, DataLine, Cpu, Lock, Bell, Connection, Delete
} from '@element-plus/icons-vue'
import MetricCard from '@/views/dashboard/components/MetricCard.vue'

// 响应式数据
const activeTab = ref('basic')
const saving = ref(false)
const loading = ref(false)

// 统计数据
const stats = reactive({
  totalSettings: 0,
  activeSettings: 0,
  pendingSettings: 0,
  version: 'v1.0.0',
  uptime: '0天0小时0分钟',
  memoryUsage: 0,
  cpuUsage: 0
})

// 基础设置
const basicSettings = reactive({
  systemInfo: {
    name: '灵犀管理系统',
    description: '企业级智能管理系统',
    version: '1.0.0',
    copyright: '© 2023 灵犀科技有限公司'
  },
  systemBehavior: {
    autoSave: true,
    autoRefresh: false,
    refreshInterval: 60,
    theme: 'light'
  }
})

// 安全设置
const securitySettings = reactive({
  passwordPolicy: {
    minLength: 8,
    requireNumber: true,
    requireSpecialChar: true,
    expirationDays: 90
  },
  loginSecurity: {
    lockOnFailedAttempts: true,
    maxFailedAttempts: 5,
    lockDuration: 30
  },
  notifications: {
    loginNotification: true,
    suspiciousLoginAlert: true,
    passwordChangeNotification: true,
    securityEventNotification: true,
    notificationMethods: ['email', 'system']
  }
})

// 网络设置
const networkSettings = reactive({
  api: {
    timeout: 10000,
    retryCount: 3,
    rateLimiting: true,
    requestsPerMinute: 1000
  },
  proxy: {
    enabled: false,
    host: '',
    port: 8080,
    authType: 'none',
    username: '',
    password: ''
  }
})

// 数据设置
const dataSettings = reactive({
  backup: {
    autoBackup: true,
    frequency: 'daily',
    keepBackups: 30,
    backupPath: '/backups'
  },
  cleanup: {
    autoCleanupLogs: true,
    logRetentionDays: 30,
    autoCleanupCache: true,
    cacheRetentionDays: 7
  }
})

// 方法
const loadSettings = async () => {
  loading.value = true
  try {
    // 模拟加载数据
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    // 更新统计数据
    stats.totalSettings = 24
    stats.activeSettings = 20
    stats.pendingSettings = 4
    stats.version = 'v1.0.0'
    stats.uptime = '30天12小时45分钟'
    stats.memoryUsage = 65
    stats.cpuUsage = 25
    
    ElMessage.success('数据加载成功')
  } catch (error) {
    ElMessage.error('数据加载失败: ' + (error as Error).message)
  } finally {
    loading.value = false
  }
}

const saveSettings = async () => {
  saving.value = true
  try {
    // 模拟保存数据
    await new Promise(resolve => setTimeout(resolve, 1500))
    ElMessage.success('设置保存成功')
  } catch (error) {
    ElMessage.error('设置保存失败: ' + (error as Error).message)
  } finally {
    saving.value = false
  }
}

const resetToDefault = async () => {
  try {
    await ElMessageBox.confirm('确定要恢复默认设置吗？此操作不可撤销。', '恢复默认设置', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    // 模拟重置数据
    basicSettings.systemInfo = {
      name: '灵犀管理系统',
      description: '企业级智能管理系统',
      version: '1.0.0',
      copyright: '© 2023 灵犀科技有限公司'
    }
    basicSettings.systemBehavior = {
      autoSave: true,
      autoRefresh: false,
      refreshInterval: 60,
      theme: 'light'
    }
    
    securitySettings.passwordPolicy = {
      minLength: 8,
      requireNumber: true,
      requireSpecialChar: true,
      expirationDays: 90
    }
    securitySettings.loginSecurity = {
      lockOnFailedAttempts: true,
      maxFailedAttempts: 5,
      lockDuration: 30
    }
    securitySettings.notifications = {
      loginNotification: true,
      suspiciousLoginAlert: true,
      passwordChangeNotification: true,
      securityEventNotification: true,
      notificationMethods: ['email', 'system']
    }
    
    networkSettings.api = {
      timeout: 10000,
      retryCount: 3,
      rateLimiting: true,
      requestsPerMinute: 1000
    }
    networkSettings.proxy = {
      enabled: false,
      host: '',
      port: 8080,
      authType: 'none',
      username: '',
      password: ''
    }
    
    dataSettings.backup = {
      autoBackup: true,
      frequency: 'daily',
      keepBackups: 30,
      backupPath: '/backups'
    }
    dataSettings.cleanup = {
      autoCleanupLogs: true,
      logRetentionDays: 30,
      autoCleanupCache: true,
      cacheRetentionDays: 7
    }
    
    ElMessage.success('已恢复默认设置')
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('恢复默认设置失败: ' + (error as Error).message)
    }
  }
}

const exportSettings = () => {
  ElMessage.info('导出配置功能待实现')
}

const manualBackup = () => {
  ElMessage.success('开始备份数据...')
  // 模拟备份过程
  setTimeout(() => {
    ElMessage.success('数据备份完成')
  }, 2000)
}

const manualCleanup = () => {
  ElMessageBox.confirm('确定要立即清理数据吗？', '数据清理', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    ElMessage.success('开始清理数据...')
    // 模拟清理过程
    setTimeout(() => {
      ElMessage.success('数据清理完成')
    }, 2000)
  }).catch(() => {
    // 用户取消
  })
}

// 生命周期
onMounted(() => {
  loadSettings()
})
</script>

<style scoped>
.system-settings {
  padding: 20px;
  background: linear-gradient(135deg, #f5f7fa 0%, #e4efe9 100%);
  min-height: 100vh;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 20px;
}

.header-left {
  flex: 1;
}

.page-title {
  margin: 0 0 12px 0;
  font-size: 24px;
  font-weight: 600;
  color: #1f2d3d;
}

.status-badges {
  display: flex;
  gap: 12px;
}

.status-badges .el-tag {
  display: flex;
  align-items: center;
  gap: 4px;
  font-weight: 500;
}

.header-actions {
  display: flex;
  gap: 12px;
  flex-shrink: 0;
}

.stats-row {
  margin-bottom: 20px;
}

.metric-card-wrapper {
  height: 100%;
}

.metric-card-custom {
  display: flex;
  align-items: center;
  padding: 20px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  height: 100%;
}

.metric-icon {
  width: 48px;
  height: 48px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 16px;
}

.metric-info {
  flex: 1;
}

.metric-value {
  font-size: 20px;
  font-weight: 600;
  color: #1f2d3d;
  margin-bottom: 4px;
}

.metric-title {
  font-size: 14px;
  color: #606266;
}

.nav-card {
  border-radius: 8px;
  overflow: hidden;
}

.settings-tabs :deep(.el-tabs__content) {
  padding: 20px 0;
}

.setting-card {
  margin-bottom: 20px;
}

.setting-header {
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: 600;
  color: #1f2d3d;
}

.form-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 4px;
}

@media (max-width: 768px) {
  .system-settings {
    padding: 16px;
  }
  
  .page-header {
    flex-direction: column;
    gap: 16px;
  }
  
  .status-badges {
    flex-wrap: wrap;
  }
  
  .header-actions {
    flex-wrap: wrap;
    justify-content: center;
  }
  
  .stats-row {
    margin-bottom: 16px;
  }
  
  .metric-card-custom {
    padding: 16px;
  }
  
  .metric-value {
    font-size: 18px;
  }
}
</style>